package com.xxx.zhujici;

import java.util.List;

import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicHierarchy;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.wallet.DeterministicSeed;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;

import com.google.common.collect.ImmutableList;

import sun.security.provider.SecureRandom;

public class ZhujiciTest {

	/**
	 * path路径
	 */
	private final static ImmutableList<ChildNumber> BIP44_ETH_ACCOUNT_ZERO_PATH = ImmutableList
			.of(new ChildNumber(44, true), new ChildNumber(60, true), ChildNumber.ZERO_HARDENED, ChildNumber.ZERO);

	/**
	 * 创建钱包
	 * 
	 * @throws MnemonicException.MnemonicLengthException
	 */
	private static void createWallet() throws MnemonicException.MnemonicLengthException {
		// 1.生成12位助记词
		SecureRandom secureRandom = new SecureRandom();
		byte[] entropy = new byte[DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8];
		secureRandom.engineNextBytes(entropy);
		List<String> str = MnemonicCode.INSTANCE.toMnemonic(entropy);
		System.out.println();
		System.out.println("助记词：");
		System.out.println(str);

		// 2.使用助记词生成钱包种子
		byte[] seed = MnemonicCode.toSeed(str, ""); // passphrase为""
		DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(seed);
		DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(masterPrivateKey);
		DeterministicKey deterministicKey = deterministicHierarchy.deriveChild(BIP44_ETH_ACCOUNT_ZERO_PATH, false, true,
				new ChildNumber(0));
		byte[] bytes = deterministicKey.getPrivKeyBytes();
		ECKeyPair keyPair = ECKeyPair.create(bytes);
		System.out.println();
		System.out.println("私钥：");
		System.out.println("0x" + keyPair.getPrivateKey().toString(16));
		System.out.println();
		System.out.println("公钥：");
		System.out.println(keyPair.getPublicKey().toString(16));

		// 3.通过公钥生成钱包地址
		String address = Keys.getAddress(keyPair.getPublicKey());
		System.out.println();
		System.out.println("地址：");
		System.out.println("0x" + address);
	}

	public static void main(String[] args) throws Exception {
		createWallet();
	}
}
